import router from '@/router'
import store from '@/store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

// 导航守卫
const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  NProgress.done()
  const { token, userInfo } = store.state.user
  if (token) {
    if (!userInfo.userName) {
      try {
        await store.dispatch('user/getUserInfo')
      } catch {
        Message.error('登录信息过期')
        store.commit('user/removeToken')
        next('/login')
        NProgress.done()
      }
    }
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach((to, from) => {
  NProgress.done()
})
